package com.coolw.spring.statemachine.support.order;

import com.coolw.spring.statemachine.constant.StateMachineConst;
import com.coolw.spring.statemachine.enums.OrderEvent;
import com.coolw.spring.statemachine.enums.OrderStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.state.State;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 订单状态转换后,执行的操作
 *
 * @author coolw
 * @date 2024/4/15 10:26
 */
@Slf4j
@Component
public class OrderStateMachineAction implements Action<OrderStatusEnum, OrderEvent> {

    @Override
    public void execute(StateContext<OrderStatusEnum, OrderEvent> context) {
        OrderContext orderContext = (OrderContext) context.getMessageHeader(StateMachineConst.CONTEXT_KEY);
        if (Objects.isNull(orderContext)) {
            log.error("orderContext信息为空,context:{}", context);
            return;
        }

        String orderId = orderContext.getOrderId();
        State<OrderStatusEnum, OrderEvent> source = context.getSource();
        State<OrderStatusEnum, OrderEvent> target = context.getTarget();
        OrderEvent event = context.getEvent();
        log.info("订单正在操作,orderId:{},from:{},to:{},on:{}", orderId, source.getId(), target.getId()
                , event);
    }
}
